//
//  ContentListCell.m
//  yigou
//
//  Created by SunChao on 17/1/11.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "ContentListCell.h"
#import "TopicContentModel.h"
#import "ArticleContentModel.h"
#import "TribeDetailViewController.h"
#import "ArticleWebViewController.h"
#import "HisHomePageViewController.h"
#import "DFToolUtil.h"

#define ToolbarWidth 200
#define ToolbarHeight 30

@implementation ContentListCell

- (void)setFrame:(CGRect)frame
{
    CGFloat kTableTopBorderWidth = 10;
    CGFloat kTableViewCellMargin = 10;
//    frame.origin.y += kTableTopBorderWidth;
    frame.size.height -= kTableViewCellMargin;
    [super setFrame:frame];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    _isLikeCommentToolbarShow = NO;
    self.converImg.layer.masksToBounds = YES;
    self.converImg.contentMode = UIViewContentModeScaleAspectFill;
    self.converImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapContentImgAction:)];
    [self.converImg addGestureRecognizer:tap];
    
    if (_timeLabel == nil) {
        _timeLabel = [[UILabel alloc]init];
        _timeLabel.frame = CGRectMake(SCREEN_WIDTH-15-150, 15, 150, 30);
        _timeLabel.textAlignment = NSTextAlignmentRight;
        _timeLabel.font = [UIFont systemFontOfSize:13];
        _timeLabel.textColor = [UIColor lightGrayColor];
        [self.contentView addSubview:self.timeLabel];
    }
    
    
    CGFloat y = CGRectGetMaxY(self.converImg.frame)+15;
   
    if (_likeCmtButton == nil) {
        _likeCmtButton = [UIButton buttonWithType:0];
        _likeCmtButton.frame = CGRectMake(SCREEN_WIDTH-15-30, y, 30, 30);
        [_likeCmtButton setImage:[UIImage imageNamed:@"AlbumOperateMore"] forState:UIControlStateNormal];
        [_likeCmtButton setImage:[UIImage imageNamed:@"AlbumOperateMoreHL"] forState:UIControlStateHighlighted];
        [_likeCmtButton addTarget:self action:@selector(onClickLikeCommentBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_likeCmtButton];
    }
    
    
    
    if (_commitButton == nil) {
        _commitButton = [UIButton buttonWithType:0];
        _commitButton.frame = CGRectMake(15, y, 40, 30);
        [_commitButton setImage:[UIImage imageNamed:@"评论"] forState:UIControlStateNormal];
        [_commitButton setTitle:@"0" forState:UIControlStateNormal];
        [_commitButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
        _commitButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_commitButton addTarget:self action:@selector(CommitButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_commitButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.contentView addSubview:_commitButton];
    }
    
    float x = CGRectGetMaxX(_commitButton.frame);
    if (_likeButton == nil) {
        _likeButton = [UIButton buttonWithType:0];
        _likeButton.frame = CGRectMake(x+15, y, 40, 30);
        [_likeButton setImage:[UIImage imageNamed:@"取消点赞"] forState:UIControlStateNormal];
        [_likeButton setTitle:@"0" forState:UIControlStateNormal];
        [_likeButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
        _likeButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_likeButton addTarget:self action:@selector(LikeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_likeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.contentView addSubview:_likeButton];
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(HiddenCommentBar) name:@"HiddenCommentBar" object:nil];
}
- (void)HiddenCommentBar{
     [self hideLikeCommentToolbar];
}
-(void)contentWithDic:(NSDictionary *)contentDic
{
    _isLikeStatus = NO;
    //    _isCollectStatus = NO;
    self.contentDic = contentDic;
    TopicContentModel *model = [[TopicContentModel alloc]initWithDictionary:contentDic error:nil];
    [self.userImg sd_setImageWithURL:[NSURL URLWithString:[model.hyUser objectForKey:@"head_url"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    self.userImg.layer.cornerRadius = 20;
    self.userImg.layer.masksToBounds = YES;
    self.userImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap0 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapUserImgAction)];
    [self.userImg addGestureRecognizer:tap0];
    self.userName.text = [model.hyUser objectForKey:@"nick_name"];
    self.tribeName.text = model.tribe_name;
    self.tribeName.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTribeNameAction:)];
    [self.tribeName addGestureRecognizer:tap];
    [self.converImg sd_setImageWithURL:[NSURL URLWithString:model.cover_img] placeholderImage:[UIImage imageNamed:@"placeholder.png"]width:SCREEN_WIDTH height:0];
    
    self.title.text = model.title;
    self.contentDesc.text = model.content_desc;
    self.timeLabel.text = [DFToolUtil preettyTime:model.publish_tm];
    if (model.plCount>0) {
        NSString *str = [NSString stringWithFormat:@"%ld",model.plCount];
        [self.commitButton setTitle:str forState:UIControlStateNormal];
    }
    if (model.likeCount>0) {
        NSString *str = [NSString stringWithFormat:@"%ld",model.likeCount];
        [self.likeButton setTitle:str forState:UIControlStateNormal];
    }
    
    
    //    if (model.iscollect == YES) {
    //        _isCollectStatus = YES;
    //    }
    
    if (_likeCommentToolbar == nil) {
        CGFloat x = CGRectGetMinX(_likeCmtButton.frame)-ToolbarWidth-10;
        CGFloat y = CGRectGetMinY(_likeCmtButton.frame);
        CGFloat width = ToolbarWidth;
        CGFloat height = ToolbarHeight;
        _likeCommentToolbar = [[WZLikeCommentToolbar alloc] initWithFrame:CGRectMake(x, y, width, height) isLikeBtnStatus:_isLikeStatus isCollectBtnStatus:0];
        _likeCommentToolbar.delegate = self;
        _likeCommentToolbar.hidden = YES;
        [self.contentView addSubview:_likeCommentToolbar];
    }
    if (model.islike == YES) {
        _isLikeStatus = YES;
    }
    [_likeCommentToolbar updateWithIsLikeBtnStatus:_isLikeStatus];
}

-(void) onClickLikeCommentBtn:(id)sender
{
    _isLikeCommentToolbarShow = !_isLikeCommentToolbarShow;
   _likeCommentToolbar.hidden = !_isLikeCommentToolbarShow;
    //动画效果
    CGFloat x = CGRectGetMinX(_likeCmtButton.frame)-ToolbarWidth-10;
    CGFloat y = CGRectGetMinY(_likeCmtButton.frame);
    CGFloat width = ToolbarWidth;
    CGFloat height = ToolbarHeight;
    _likeCommentToolbar.layer.anchorPoint =CGPointMake(0.5,0.5);//设置锚点
    _likeCommentToolbar.frame = CGRectMake(x + width / 2, y, width, height);
    if (_isLikeCommentToolbarShow) {
        CABasicAnimation *theAnimation;
        theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
        theAnimation.duration=0.2;
        theAnimation.removedOnCompletion = YES;
        
        theAnimation.fromValue = [NSNumber numberWithFloat:0];
        theAnimation.toValue = [NSNumber numberWithFloat:1];
        _likeCommentToolbar.layer.anchorPoint =CGPointMake(1.0,0.5);
        [_likeCommentToolbar.layer addAnimation:theAnimation forKey:@"animateTransform"];
    }
}

-(void)hideLikeCommentToolbar
{
    if (_isLikeCommentToolbarShow == NO) {
        return;
    }
    _isLikeCommentToolbarShow = NO;
    _likeCommentToolbar.hidden = YES;
}


#pragma mark -WZLikeCommentToolbarDelegate
-(void)onLike
{
    NSString *contentId = [self.contentDic objectForKey:@"content_id"];
    
    [self requestDianZanWithContentId:contentId];
    
    [self hideLikeCommentToolbar];
}

- (void)onComment
{
    [self PushToArticleWebViewController];
}

- (void)onShare
{
    [self hideLikeCommentToolbar];
    [self clickShare];
    
}
#pragma mark -分享跳转
- (void)clickShare {
    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
    cusSheet.delegate = self;
    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
                              @{@"name":@"微信",@"icon":@"sns_wx"},
                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},];
    
    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
}

- (void)customActionSheetButtonClick:(YXActionSheetButton *)btn {
    NSLog(@"第%li个按钮被点击了",(long)btn.tag);
    NSInteger index = btn.tag;
    
    DyShareType type;
    switch (index) {
        case 0:
            type = DyShareTypePengYouQuan;
            break;
        case 4:
            type = DyShareTypeQZone;
            break;
        case 2:
            type = DyShareTypeWeiBo;
            break;
        case 1:
            type = DyShareTypeWeiXin;
            break;
        case 3:
            type = DyShareTypeQQ;
            break;
        default:
            break;
    }
    [[DyShare getInstance]shareWithShareType:type Content:[self.contentDic objectForKey:@"content_desc"] title:[self.contentDic objectForKey:@"title"] url:[self.contentDic objectForKey:@"shareUrl"] image:self.converImg.image delegate:nil];
}


//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            NSLog(@"nextResponder:%@",nextResponder);
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

- (void)tapUserImgAction{
     UIViewController *vc = [self getCurrentVC];
    HisHomePageViewController *homepage  = [[HisHomePageViewController alloc]init];
    homepage.userid = [self.contentDic objectForKey:@"user_id"];
    [vc.navigationController pushViewController:homepage animated:YES];
}
- (void)tapTribeNameAction:(UITapGestureRecognizer *)tap{
    
    UIViewController *vc = [self getCurrentVC];
    //在部落详情里点击部落详情未处理
    if ([vc isKindOfClass:[TribeDetailViewController class]]) {
        TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
        [vc.navigationController pushViewController:detail animated:YES];
        detail.tribeID =  [self.contentDic objectForKey:@"tribe_id"];
    }else{
        TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
        [vc.navigationController pushViewController:detail animated:YES];
        detail.tribeID = [self.contentDic objectForKey:@"tribe_id"];
    }
}


- (void)CommitButtonAction:(id)sender{
    
    [self PushToArticleWebViewController];
    
}
- (void)LikeButtonAction:(id)sender{
    
    [self PushToArticleWebViewController];
}

- (void)TapContentImgAction:(UITapGestureRecognizer *)tap{
    [self PushToArticleWebViewController];
}
- (void)PushToArticleWebViewController
{
    UIViewController *vc =  [self getCurrentVC];
    ArticleWebViewController *articel = [[ArticleWebViewController alloc]initWithNibName:@"ArticleWebViewController" bundle:nil];
    articel.articleContent = [self.contentDic objectForKey:@"content_id"];
    articel.articleUserId  = [self.contentDic objectForKey:@"user_id"];;
    articel.articleTribeId = [self.contentDic objectForKey:@"tribe_id"];;
    articel.shareimgurl    = [self.contentDic objectForKey:@"shareUrl"];;
    articel.sharetitle     = [self.contentDic objectForKey:@"title"];
    articel.sharedesc       = [self.contentDic objectForKey:@"content_desc"];
    articel.shareurl       = [self.contentDic objectForKey:@"shareUrl"];
    [vc.navigationController pushViewController:articel animated:YES];
}

#pragma mark -点赞、取消点赞请求
- (void)requestDianZanWithContentId:(NSString *)contentId{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *content_id = contentId;
    NSString *status = @"";
    if (_isLikeStatus == YES) {
        //点赞状态00点赞01取消点赞
        status = @"01";
    }else{
        status = @"00";
    }
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/setContentLike?content_id=%@&status=%@", APIYIGOU, content_id,status];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
         _isLikeStatus = !_isLikeStatus;
         TopicContentModel *model = [[TopicContentModel alloc]initWithDictionary:self.contentDic error:nil];
        NSString *likecount = [NSString stringWithFormat:@"%ld",model.likeCount];
        if (model.islike) {
            if (_isLikeStatus == YES) {
                [ViewFactory showSuccess:@"点赞成功"];
                NSInteger likeNum = [likecount integerValue];
                NSString *likeNumStr = [NSString stringWithFormat:@"%ld",likeNum];
                [_likeButton setTitle:likeNumStr forState:UIControlStateNormal];
            }else{
                [ViewFactory showSuccess:@"取消点赞成功"];
                NSInteger likeNum = [likecount integerValue]-1;
                NSString *likeNumStr = [NSString stringWithFormat:@"%ld",likeNum];
                [_likeButton setTitle:likeNumStr forState:UIControlStateNormal];
            }
        }else{
            if (_isLikeStatus == YES) {
                [ViewFactory showSuccess:@"点赞成功"];
                NSInteger likeNum = [likecount intValue]+1;
                NSString *likeNumStr = [NSString stringWithFormat:@"%ld",likeNum];
                [_likeButton setTitle:likeNumStr forState:UIControlStateNormal];
            }else{
                [ViewFactory showSuccess:@"取消点赞成功"];
                NSInteger likeNum = [likecount intValue];
                NSString *likeNumStr = [NSString stringWithFormat:@"%ld",likeNum];
                [_likeButton setTitle:likeNumStr forState:UIControlStateNormal];
            }
        }
       
        
        [_likeCommentToolbar updateWithIsLikeBtnStatus:_isLikeStatus];
        
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
    
}

//- (void)requestQuXiaoShouCang{
//    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *content_id = [self.contentDic  objectForKey:@"content_id"];
//    NSString *url = [NSString stringWithFormat:@"%@/hyContent/delCollect?becollect_id=%ld",APIYIGOU, [content_id integerValue]];
//    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        
//        [ViewFactory showSuccess:@"取消收藏成功"];
//        
//    } error:^(YTKBaseRequest *request) {
//        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
//        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
//    } failure:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:NETWORK_ERR];
//        
//    }];
//}
//- (void)requestShouCang{
//    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *content_id = [self.contentDic objectForKey:@"content_id"];
//    NSString *becollect_type = @"01";//01表示收藏内容
//    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addCollect?becollect_id=%ld&becollect_type=%@",APIYIGOU, [content_id integerValue],becollect_type];
//    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        
//        [ViewFactory showSuccess:@"收藏成功"];
//        
//    } error:^(YTKBaseRequest *request) {
//        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
//        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
//    } failure:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:NETWORK_ERR];
//        
//    }];
//}

//- (void)loadNetworkQuXiaoGuanZhuData{
//    
//    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *follow_obj_id = [self.contentDic  objectForKey:@"user_id"];
//    NSString *url = [NSString stringWithFormat:@"%@/userCenter/qxAttountByUserId?follow_obj_type=00&follow_obj_id=%ld", APIYIGOU,[follow_obj_id integerValue]];
//    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        NSLog(@"------%@",request);
//        [self.addBtn setBackgroundColor:QINGColor];
//        self.addBtn.selected = NO;
//        [ViewFactory showSuccess:@"取消关注成功"];
//    } error:^(YTKBaseRequest *request) {
//        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
//        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
//    } failure:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:NETWORK_ERR];
//        
//    }];
//
//}
//- (void)loadNetworkGuanZhuData {
//    
//    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *follow_obj_id = [self.contentDic  objectForKey:@"user_id"];
//    NSString *url = [NSString stringWithFormat:@"%@/hytribe/setConcern?follow_obj_id=%ld", APIYIGOU, [follow_obj_id integerValue]];
//    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        NSLog(@"------%@",request);
//        [self.addBtn setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
//        self.addBtn.selected = YES;
//        [ViewFactory showSuccess:@"关注成功"];
//    } error:^(YTKBaseRequest *request) {
//        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
//        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
//    } failure:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:NETWORK_ERR];
//        
//    }];
//}



@end
